﻿using System;
using System.Drawing;
using System.IO;
using System.Windows;
using Utility;
using static Utility.WinAPI;
using WallpaperEngine.Core;

namespace WallpaperEngine
{
    public class Wallpaper
    {
        public IntPtr Handle { get;private set; }

        public dynamic Window { get; set; }

        public Rectangle Fullscreen { get; }

        private string oldWallpaperFolder;

        private WallpaperCore wallpaperCore;

        public Wallpaper()
        {
            Fullscreen = Common.GetFullscreen();
            oldWallpaperFolder = $"C:\\Users\\{Environment.UserName}\\AppData\\Roaming\\Microsoft\\Windows\\Themes\\CachedFiles\\";
            SendMessage(FindWindow("Progman", null), 0x052C, 0, 0);
            EnumWindows(((tophandle, _) =>
            {
                if (FindWindowEx(tophandle, IntPtr.Zero, "SHELLDLL_DefView", string.Empty) != IntPtr.Zero)
                {
                    Handle = FindWindowEx(IntPtr.Zero, tophandle, "WorkerW", string.Empty);
                    return false;
                }
                return true;
            }), IntPtr.Zero);
            if (Handle == IntPtr.Zero)
            {
                throw new StartException("未能找到壁纸层", "Wallpaper.Wallpaper");
            }

            if (!string.IsNullOrWhiteSpace(Configuration.Config.CurrentWallpaper) && Common.IsPowerOnline())
            {
                SetWallpaper(PathManager.DataFolder + Configuration.Config.CurrentWallpaper);
            }
        }

        public void Close()
        {
            if (Window != null) 
            {
                Window.Close();
                Window = null;
            }
        }

        public void ToOldWallpaper()
        {
            try
            {
                foreach (var file in new DirectoryInfo(oldWallpaperFolder).GetFiles())
                {
                    if (file.Name.Contains(Fullscreen.Height.ToString()) && file.Name.Contains(Fullscreen.Width.ToString()))
                    {
                        Graphics.FromHdc(GetDC(Handle)).DrawImage(Image.FromFile(file.FullName), Fullscreen);
                        break;
                    }
                }
            }
            catch (FileNotFoundException exception)
            {
                MessageBox.Show($"{exception.Data.ToString()}\n{exception.Message}\n{exception.Source}\n{exception.StackTrace}\n{exception.TargetSite}\n很抱歉, 我们未能找到您原来的壁纸QAQ, 请手动恢复\n请将本窗口截图发给作者,谢谢");
            }
            catch (Exception exception)
            {
                MessageBox.Show($"{exception.Data.ToString()}\n{exception.Message}\n{exception.Source}\n{exception.StackTrace}\n{exception.TargetSite}\n很抱歉,在应用原壁纸时出现异常! \n请将本窗口截图发给作者,谢谢");
            }
        }

        public void SetWallpaper(string fullPath)
        {
            Configuration.Config.CurrentWallpaper = Path.GetFileName(fullPath);
            wallpaperCore = WallpaperCore.GetWallpaperCore(this);
        }
    }
}
